/**
@author		Jong Min, Lee
@date		  10/01/2014
@breif		dicom instance class 

copyright(c) Tae Young Soft. All right reserved. 2014
*/
#include "stdafx.h"
#include "Taurus_DcmData/DcmInstance.h"

#include "Taurus_DcmData/DcmFrame.h"
#include "Taurus_DcmData/IInstanceInfo.h"

CDcmInstance::CDcmInstance()
{
  init();
}

CDcmInstance::~CDcmInstance()
{
  destroy();
}

unsigned CDcmInstance::getNumFrames() const
{
  return m_theFrames.size();
}

CDcmFrame* CDcmInstance::getFrame(const unsigned int index)
{
  if(index >= m_theFrames.size()) return nullptr;
  return m_theFrames[index];
}

const CDcmFrame* CDcmInstance::getFrame(const unsigned int index) const
{
  if(index >= m_theFrames.size()) return nullptr;
  return m_theFrames[index];
}

void CDcmInstance::init()
{
  m_theRefCount = 0;
  m_theParent = nullptr;
  m_theKey = _T("");
  m_theSOPClassUID = _T("");
}

void CDcmInstance::destroy()
{
  removeAllFrames();
}

void CDcmInstance::removeAllFrames()
{
  unsigned num = m_theFrames.size();
  for(unsigned i = 0; i < num; ++i)
    _DELETE(m_theFrames[i]);
  m_theFrames.clear();
}

DWORD CDcmInstanceProducer::produce(IInstanceInfo& instanceInfo, 
                                    CDcmSeries* parent, 
                                    CDcmInstance* outInstance)
{
  CDcmInstance* newInstance = nullptr;
  _TRY_ALLOC(newInstance, CDcmInstance);
  if(newInstance == nullptr) return ERROR_NOT_ENOUGH_MEMORY;

  DWORD error = ERROR_SUCCESS;

  //parent series
  newInstance->m_theParent = parent;
  //key
  newInstance->m_theKey = instanceInfo.getKey();
  //sop class uid
  newInstance->m_theSOPClassUID = instanceInfo.getSOPClassUID();

  //create frames
  int numFrameInfo = instanceInfo.getNumFrameInfo();
  if(numFrameInfo <= 0) return ERROR_SUCCESS;

  _TRY_BEGIN
  newInstance->m_theFrames.reserve(numFrameInfo);
  _CATCH_ALL
  _DELETE(newInstance);
  return ERROR_NOT_ENOUGH_MEMORY;
  _CATCH_END

  for(int i = 0; i < numFrameInfo; ++i)
  {
    IFrameInfo* frameInfo = instanceInfo.getFrameInfo(i);
    if(frameInfo == nullptr) continue;

    CDcmFrame* newFrame = nullptr;
    error = CDcmFrameProducer::produce(*frameInfo, newInstance, newFrame);
    if(error != ERROR_SUCCESS)
    {
      _DELETE(newInstance);
      return error;
    }

    newInstance->m_theFrames.push_back(newFrame);
  }

  outInstance = newInstance;

  return ERROR_SUCCESS;
}